package com.lanxin.hr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lanxin.hr.entity.ZzDepartment;
import com.lanxin.hr.entity.ZzDepartmentJob;
import com.lanxin.hr.entity.ZzEmployee;
import com.lanxin.hr.mapper.ZzDepartmentJobMapper;
import com.lanxin.hr.mapper.ZzDepartmentMapper;
import com.lanxin.hr.mapper.ZzEmployeeMapper;
import com.lanxin.hr.service.IZzDepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lanxin.hr.vo.DeptVo;
import com.lanxin.hr.vo.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.security.PublicKey;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-07-21
 */
@Service
public class ZzDepartmentServiceImpl extends ServiceImpl<ZzDepartmentMapper, ZzDepartment> implements IZzDepartmentService {

    @Autowired
    private ZzDepartmentMapper departmentMapper;

    @Autowired
    private ZzDepartmentJobMapper departmentJobMapper;

    @Autowired
    private ZzEmployeeMapper employeeMapper;

    //分页查询所有的部门信息，以及按条件查询
    @Override
    public PageVo<DeptVo> ListDeptVo(Integer page, Integer pageSize, ZzDepartment department) {

        if(pageSize == null || pageSize < 1){
            pageSize = 5;
        }

        //总记录数
        int rowcount=departmentMapper.countDept(department);
        //总页数
        int pageCount= (int)Math.ceil((double)rowcount/pageSize);

        if(page == null || page < 1){
            page = 1;
        } else if (page>pageCount) {
            page = pageCount;
        }

        //查询条件
        Map<String, Object> map = new HashMap<>();
        map.put("page", (page-1)*pageSize);
        map.put("pageSize", pageSize);
        map.put("department", department);

        //查询所有的deptVo
        List<DeptVo> deptVos=departmentMapper.ListDeptVo(map);
        //生成分页对象
        PageVo<DeptVo> pageVo=new PageVo<>();
        pageVo.setPage(page);
        pageVo.setPageSize(pageSize);
        pageVo.setRowcount(rowcount);
        pageVo.setPageCount(pageCount);
        pageVo.setData(deptVos);
        return pageVo;
    }

    //查询所有部门信息
    @Override
    public List<ZzDepartment> listDepartment() {
        return departmentMapper.selectList(null);
    }

    //获得所有部门的id和部门名称
    @Override
    public List<ZzDepartment> getDeptName() {
        List<ZzDepartment> deptName=departmentMapper.selectList(null);
        List<ZzDepartment> parents=new ArrayList<>();
        for(ZzDepartment dept:deptName){
            ZzDepartment parent=new ZzDepartment();
            parent.setOid(dept.getOid());
            parent.setDeptName(dept.getDeptName());
            parents.add(parent);
        }
        return parents;
    }

    //添加部门及部门职位对应表
    @Override
    public void addDept(ZzDepartment department,List<Integer> jobsId) {
        //添加部门
        int row= departmentMapper.insert(department);
        //添加部门对应的职位
        if(row>0){
            for(Integer jobId:jobsId){
                ZzDepartmentJob departmentJob=new ZzDepartmentJob();
                departmentJob.setDeptid(department.getOid());
                departmentJob.setJobid(jobId);
                departmentJobMapper.insert(departmentJob);
            }
        }

    }

    //检查添加的部门是否已经存在
    @Override
    public boolean checkAddDept(String deptName) {
        QueryWrapper<ZzDepartment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deptName", deptName);
        ZzDepartment department = departmentMapper.selectOne(queryWrapper);
        boolean flag=true;
        if(department != null){
            flag=false;
        }
        return flag;
    }

    //根据部门id查询部门信息
    @Override
    public DeptVo getDeptVoById(Integer oid) {
        return departmentMapper.getDeptVoById(oid);
    }

    //根据部门名称查询部门信息
    @Override
    public ZzDepartment getdeptByName(String deptName) {
        QueryWrapper<ZzDepartment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deptName", deptName);
        return departmentMapper.selectOne(queryWrapper);
    }

    //验证更新的部门名称是否重复
    @Override
    public boolean checkUpdateDept(String deptName, Integer oid) {
        //检测数据库中是否已经有相同名称的部门
        ZzDepartment oldDepartment= getdeptByName(deptName);
        boolean flag=true;
        if(oldDepartment!=null){
            //若已经存在则检查两者的oid是否相同，相同则放行
            Integer oldId=oldDepartment.getOid();
            //比较新旧id，若不一致则拦截
            if(oldId!=oid){
                flag=false;
            }
        }
        return flag;
    }

    //根据部门id删除部门
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteDeptById(Integer oid) {
        // 1. 检查部门是否有员工
        if (!employeeMapper.selectList(new QueryWrapper<ZzEmployee>().eq("deptid", oid)).isEmpty()) {
            return false;
        }

        try {
            // 2. 尝试删除部门
            int deleted = departmentMapper.deleteById(oid);
            if (deleted == 0) {
                return false; // 部门不存在
            }

            // 3. 删除关联职位（只有部门删除成功后才执行）
            departmentJobMapper.deleteByDId(oid);
            return true;

        }catch (Exception e) {
            log.error("删除部门异常", e);
            throw new RuntimeException("删除部门失败", e);
        }

    }

}
